<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>KonvaJS Sandbox</title>
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, user-scalable=1.0, minimum-scale=1.0, maximum-scale=1.0"
    />
    <style>
      body {
        margin: 0;
      }
    </style>
    <!-- <script src="https://cdn.rawgit.com/hammerjs/touchemulator/master/touch-emulator.js"></script> -->
    <script>
      // TouchEmulator();
    </script>
    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.7/hammer.js"></script> -->
    <!-- <script src="https://cdn.rawgit.com/hammerjs/touchemulator/master/touch-emulator.js"></script> -->
    <!-- <script src="./hammer.js"></script> -->
  </head>

  <body>
    <div id="container"></div>
    <script type="module">
      import Konva from '../src/index.ts';
      const stage = new Konva.Stage({
        container: 'container',
        width: window.innerWidth,
        height: window.innerHeight,
      });

      const layer = new Konva.Layer();
      stage.add(layer);

      const cellWidth = stage.width() / 10;
      const cellHeight = stage.width() / 10;

      for (var i = 0; i < 10; i++) {
        layer.add(
          new Konva.Line({
            x: i * cellWidth,
            points: [0, 0, 0, stage.height()],
            stroke: 'black',
            strokeWidth: 1,
          })
        );
      }

      for (var i = 0; i < 10; i++) {
        layer.add(
          new Konva.Line({
            y: i * cellHeight,
            points: [0, 0, stage.width(), 0],
            stroke: 'black',
            strokeWidth: 1,
          })
        );
      }

      const rect = new Konva.Rect({
        x: 90,
        y: 90,
        width: 100,
        height: 100,
        fill: 'red',
        draggable: true,
      });
      layer.add(rect);

      const tr = new Konva.Transformer({
        nodes: [rect],
        anchorDragBoundFunc: function (oldPos, pos, event) {
          const closestX = Math.round(pos.x / cellWidth) * cellWidth;
          const diffX = Math.abs(pos.x - closestX);

          const closestY = Math.round(pos.y / cellHeight) * cellHeight;
          const diffY = Math.abs(pos.y - closestY);

          const snappedX = diffX < 10;
          const snappedY = diffY < 10;

          if (snappedX && !snappedY) {
            return {
              x: closestX,
              y: oldPos.y,
            };
          } else if (snappedY && !snappedX) {
            return {
              x: oldPos.x,
              y: closestY,
            };
          } else if (snappedX && snappedY) {
            return {
              x: closestX,
              y: closestY,
            };
          } else {
            return {
              x: pos.x,
              y: pos.y,
            };
          }
        },
      });
      layer.add(tr);
    </script>
  </body>
</html>
